﻿	/**
 * Controller for all tracing-related management functionality
 */
Ext.define('Sisconsolid.controller.Tracing', {
    extend: 'Sisconsolid.controller.Base',
    stores: [
        'Tracings'
    ],
    views: [
        'tracing.edit.Form',
        'tracing.edit.Window'
    ],
    refs: [
        {
            ref: 'TracingEditWindow',
            selector: '[xtype=tracing.edit.window]'
        },
        {
            ref: 'TracingEditForm',
            selector: '[xtype=tracing.edit.form]'
        } 
    ],
    init: function() {
        this.listen({
            controller: {},
            component: {
                'window[xtype=tracing.edit.window] button#save': {
                    click: this.save
                },
                'window[xtype=tracing.edit.window] button#cancel': {
                    click: this.close
                },
                'window[xtype=tracing.edit.window] button#remove': {
                    click: this.remove
                }
            },
            global: {},
            store: {},
            proxy: {} 
        });
    },/**
     * Persists edited record
     * @param {Ext.button.Button} button
     * @param {Ext.EventObject} e
     * @param {Object} eOpts
     */
    save: function( button, e, eOpts ) {
        var me = this,
            win = button.up( 'window' ),
            form = win.down( 'form' ),
            record = form.getRecord(),
            values = form.getValues(),
            callbacks;

        // set values of record from form
        record.set( values );
		// check if form is even dirty...if not, just close window and stop everything...nothing to see here
        if( !record.dirty ) {
            win.close();
            return;
        }
		if (record.data.idTracingType != 1 &&
				record.data.idTracingType != 3) {
			win.down( 'form' ).down('textfield[name=timeAccomplished]').allowBlank = true;		
		}
		if (!form.isValid()) {
			Ext.Msg.alert(translations.error, translations.enterAllFieldsMessage);
			return;
		}
		// mask to prevent extra submits
        Ext.getBody().mask(translations.savingTracing);
        // setup generic callback config for create/save methods
        callbacks ={
            success: function( tracing ) {
				Ext.Msg.alert(translations.result, translations.successSavingTracing);
                win.close();
				me.getController('Consolidation').refresh();
            },
            failure: function( records, operation ) {
            }
        };
        
        // var tracing = Ext.ModelManager.create(record.data,'Sisconsolid.model.Tracing');
		// tracing.save(callbacks);
		record.save(callbacks);
    },
    /**
     * Persists edited record
     * @param {Ext.button.Button} button
     * @param {Ext.EventObject} e
     * @param {Object} eOpts
     */
    close: function( button, e, eOpts ) {
        var me = this,
            win = button.up( 'window' );
        // close the window
        win.close();
    },
    /**
     * Displays context menu 
     * @param {Ext.data.Model[]} record
     */
    remove: function( button, e, eOpts ) {
        var me = this,
            win = button.up( 'window' ),
            form = win.down( 'form' ),
            record = form.getRecord();

        // show confirmation before continuing
        Ext.Msg.confirm( translations.attention, translations.confirmRemoveTracing, function( buttonId, text, opt ) {
            if( buttonId=='yes' ) {
				Ext.getBody().mask(translations.removingTracing);
                record.destroy({
                    success: function( tracing ) {
						Ext.Msg.alert(translations.result, translations.successRemovingTracing);
						win.close();
						me.getController('Consolidation').refresh();
					},
					failure: function( records, operation ) {
						Ext.Msg.alert(translations.result, translations.errorRemovingTracing);
					}
                })
            }
        })
    },
    /**
     * Displays common editing form for add/edit operations
     * @param {Ext.data.Model} record
     */
    showEditWindow: function( record ) {
        var me = this,
            win = me.getTracingEditWindow(),
            isNew = record.phantom;
        // if window exists, show it; otherwise, create new instance
        if( !win ) {
            win = Ext.widget( 'tracing.edit.window', {
                title: isNew ? translations.addTracing : translations.editTracing
            });
        }
		if (record.data.idTracingType != 1 &&
				record.data.idTracingType != 3) {
			win.down( 'form' ).down('textfield[name=timeAccomplished]').hide();		
		}
		if (isNew) {
			win.down( 'button[itemId=remove]').hide();
		}
        // show window
        win.show();
        // load form with data
        win.down( 'form' ).loadRecord( record );
    },
	processTracing: function(idTracing, idConsolidation, idTracingType, tracingType, need, idCell) {
		var me = this, tracing = Ext.create('Sisconsolid.model.Tracing');
		if (idTracing != null) {
			var loaderTracing = Ext.ModelManager.getModel('Sisconsolid.model.Tracing');
			loaderTracing.load(idTracing,{
				scope:this,
				success: function(queriedTracing) {
					tracing.set(queriedTracing.data);
					me.initProcessTracing(tracing, idConsolidation, idTracingType, tracingType);
				}
			});
		} else {
			tracing.set('idTracing', idTracing);
			tracing.set('need', need);
			tracing.set('idCell', idCell);
			me.initProcessTracing(tracing, idConsolidation, idTracingType, tracingType);
		}		
	},
	initProcessTracing: function(tracing, idConsolidation, idTracingType, tracingType) {
		var me = this;
		tracing.set('idConsolidation', idConsolidation);
		tracing.set('idTracingType', idTracingType);
		tracing.set('tracingType', tracingType);
		me.showEditWindow(tracing);
	}
	
});